package com.neusoft.ysu.populationmanagement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.neusoft.ysu.populationmanagement.constant.Errors;
import com.neusoft.ysu.populationmanagement.constant.TabelDic;
import com.neusoft.ysu.populationmanagement.entity.*;
import com.neusoft.ysu.populationmanagement.mapper.*;
import com.neusoft.ysu.populationmanagement.service.*;
import com.neusoft.ysu.populationmanagement.vo.VFloPop;
import com.neusoft.ysu.populationmanagement.vo.VImpPop;
import com.neusoft.ysu.populationmanagement.vo.VResPop;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * <p>
 * VIEW 服务实现类
 * </p>
 *
 * @author 作者：赵子鉴
 * @since 2024-06-18
 */
@Service
public class VResPopServiceImpl implements IVResPopService {

    @Autowired
    private VResPopMapper vResPopMapper;
    @Autowired
    private IResPopService resPopService;
    @Autowired
    private IPopulationService populationService;
    @Autowired
    private IHouseholdService householdService;
    @Autowired
    private IOperationLogService operationLogService;
    @Autowired
    private IPoliceStationService policeStationService;
    @Autowired
    private IIdnumSequenceService iIdnumSequenceService;


    /**
     * @param vResPop
     * @param operationLog
     * @return 1代表户口立户成功，101代表失败
     * 流程为更新population表和ResPop表，插入Household表，插入log表
     * @author 张幸晔
     * @date 2024-06-19 14:44
     */

    @Override
    public CommonResult houseHoldRegistered(VResPop vResPop, OperationLog operationLog) {
        Population population = new Population(vResPop);
        ResPop resPop = new ResPop(vResPop);
        Household household = new Household(vResPop, operationLog);
        //校验传人信息和数据库信息是否对应
        CommonResult checkPop = populationService.checkPop(population);
        if (checkPop.getCode() != 1) {
            checkPop.setCode(Errors.ERROR_RES_REGISTER);
            return checkPop;
        }
        //更新population表中内容
        CommonResult updatePop = populationService.updatePop(population);
        if (updatePop.getCode() != 1) {
            updatePop.setCode(Errors.ERROR_RES_REGISTER);
            return updatePop;
        }

        //检索此人是不是常住人口，如果不是则是新增respop，如果是则是更新
        CommonResult nowResPop = resPopService.selectRPBYPopId(((Population) checkPop.getResult()).getId());
        //根据popid更新Respop表
        population = (Population) checkPop.getResult();//获取到当前用户的id给popid赋值
        resPop.setPopId(population.getId());
        household.setHolderId(population.getId());
        if (nowResPop.getCode() != 1) {
            //如果不存在则是其它人口立户，变为常住人口执行insert操作
            CommonResult insertResPop = resPopService.insertResPop(resPop);
            if (insertResPop.getCode() != 1) {
                insertResPop.setCode(Errors.ERROR_RES_REGISTER);
                return insertResPop;
            }
        } else {//已是常住人口不是户主更新
            //检验此人是不是户主，如果是户主则不允许重新立户,通过检验resPop表中存储的relation字段判断
            if (((ResPop) nowResPop.getResult()).getRelationId() == 1) {//判断是否为户主
                return new CommonResult<>(Errors.ERROR_RES_REGISTER, "户主不允许重复立户", null);
            }

            CommonResult updateRP = resPopService.updateRP(resPop);
            if (updatePop.getCode() != 1) {
                updatePop.setCode(Errors.ERROR_RES_REGISTER);
                return updateRP;
            }
        }

        //插入户口表
        CommonResult insertHousehold = householdService.insertHousehold(household);
        if (insertHousehold.getCode() != 1) {
            insertHousehold.setCode(Errors.ERROR_RES_REGISTER);
            return insertHousehold;
        }
        //插入日志表
        int fillLog = operationLogService.fillOperationLog(operationLog, population.getIdnum());
        if (fillLog != 1) {
            return new CommonResult<>(0, "日志插入失败", null);
        }
        //返回成功结果
        return new CommonResult<>(1, "户口立户成功", null);
    }

    /**
     * @param idNum
     * @return com.neusoft.ysu.populationmanagement.entity.CommonResult
     * @author 张幸晔
     * @date 2024-06-20 09:59
     * 常住人口信息，查监护人、注销人、投靠人都是这个函数
     */
    @Override
    public CommonResult selectGuardianInfo(String idNum) {
        LambdaQueryWrapper<VResPop> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(VResPop::getIdnum, idNum).eq(VResPop::getIsDelete, 0);
        List<VResPop> vResPops = vResPopMapper.selectList(lambdaQueryWrapper);
        if (vResPops.size() <= 0) {
            return new CommonResult<>(0, "未查到常住人口信息", null);
        }
        return new CommonResult(1, "常住人口信息", vResPops.get(0));

    }

    /**
     * @param vResPop
     * @param operationLog
     * @return com.neusoft.ysu.populationmanagement.entity.CommonResult
     * @author 张幸晔
     * @date 2024-06-20 14:48
     * 出生申报，其实应该叫户口申报因为还有领养，emm不过都一样随便了
     */
    @Override
    public CommonResult birthDeclaration(VResPop vResPop, OperationLog operationLog) {
        //根据operationlog中的pid去查派出所的信息，调用policestationService函数
        CommonResult policeStationResult = policeStationService.selectPoliceStationInfoByPid(operationLog.getPid());
        if (policeStationResult.getCode() != 1) {
            policeStationResult.setCode(Errors.ERROR_RES_DECLAREATION);
            return policeStationResult;
        }
        PoliceStation policeStation = (PoliceStation) policeStationResult.getResult();
        //根据常住人口信息和警察局信息生成身份证号
        String idNum = generateIdNum(vResPop, policeStation);

        Population population = new Population(vResPop);
        ResPop resPop = new ResPop(vResPop);
        population.setIdnum(idNum);
        CommonResult insertPop = populationService.insertPop(population);
        if (insertPop.getCode() != 1) {
            insertPop.setCode(Errors.ERROR_RES_DECLAREATION);
            return insertPop;
        }
        //根据插入的population主键插入resPop
        resPop.setPopId(((Population) insertPop.getResult()).getId());
        CommonResult insertResPop = resPopService.insertResPop(resPop);
        if (insertResPop.getCode() != 1) {
            insertResPop.setCode(Errors.ERROR_RES_DECLAREATION);
            return insertResPop;
        }

        int fillLog = operationLogService.fillOperationLog(operationLog, population.getIdnum());
        if (fillLog != 1) {
            return new CommonResult<>(0, "日志插入失败", null);
        }
        vResPop.setIdnum(idNum);
        //返回成功结果
        return new CommonResult<>(1, "户口申报成功", vResPop);

    }

    /**
     * @param vResPop
     * @param operationLog
     * @return com.neusoft.ysu.populationmanagement.entity.CommonResult
     * @author 张幸晔
     * @date 2024-06-20 15:56
     * 户口注销
     */
    @Override
    public CommonResult householdLogout(VResPop vResPop, OperationLog operationLog) {
        Population population = new Population(vResPop);
        ResPop resPop = new ResPop(vResPop);
        //更新日志表
        int fillLog = operationLogService.fillOperationLog(operationLog, population.getIdnum());
        if (fillLog != 1) {
            return new CommonResult<>(0, "日志插入失败", null);
        }
        //执行population表删除
        CommonResult deletePop = populationService.deletePop(population);
        if (deletePop.getCode() != 1) {
            deletePop.setCode(Errors.ERROR_RES_Migrate);
            return deletePop;
        }
        //删除ResPop表
        CommonResult deleteResPop = resPopService.deleteResPopByPopId(((Population) deletePop.getResult()).getId());
        if (deleteResPop.getCode() != 1) {
            deleteResPop.setCode(Errors.ERROR_RES_Migrate);
            return deleteResPop;
        }
        //如果当前注销人是户主，检索是否户主还有人，没有人返回null，有人返回数组
//        CommonResult selectPersonsInHousehold;
        if (resPop.getRelationId() == 1) {
            //检索户中还有多少人
//            selectPersonsInHousehold = resPopService.selectRPByHouseNum((resPop.getHousenum()));
            CommonResult selectPersonsInHousehold = selectByHouseNum(resPop.getHousenum());
//            if (selectPersonsInHousehold.getCode() != 1) {
//                selectPersonsInHousehold.setCode(Errors.ERROR_RES_Migrate);
//                return selectPersonsInHousehold;
//            }
            if (((List<Population>) selectPersonsInHousehold.getResult()).size() == 0) {
                return new CommonResult<>(1, "注销成功", null);
            }
            return selectPersonsInHousehold;

        }

        //不是户主已经注销成功
        return new CommonResult<>(1, "注销成功", null);

    }


    /**
     * @param vResPops
     * @param operationLog
     * @return CommonResult:103失败，1成功
     * @description 将户口注销时传来的户口本中其它用户的关系进行变更
     * @author 张幸晔
     * @date 2024-06-21 09:41
     */
    @Override
    public CommonResult changeHouseholdRelation(List<VResPop> vResPops, OperationLog operationLog) {
        for (VResPop vResPop : vResPops) {
            //更新marry_id
            Population population = new Population(vResPop);
            CommonResult updatePop = populationService.updatePop(population);
            if (updatePop.getCode() != 1) {
                updatePop.setCode(Errors.ERROR_RES_Migrate);
                return updatePop;
            }
            //更新relation_id
            ResPop resPop = new ResPop(vResPop);
            CommonResult updateResPop = resPopService.updateRP(resPop);
            if (updateResPop.getCode() != 1) {
                updateResPop.setCode(Errors.ERROR_RES_Migrate);
                return updateResPop;
            }
            //更新日志表
            int fillLog = operationLogService.fillOperationLog(operationLog, population.getIdnum());
            if (fillLog != 1) {
                return new CommonResult<>(0, "日志插入失败", null);
            }
        }
        return new CommonResult<>(1, "关系变更成功", null);
    }

    /**
     * @param vResPop
     * @param operationLog
     * @return CommonResult：1，104
     * @description 户口迁移
     * @author 张幸晔
     * @date 2024-06-21 16:25
     */

    @Override
    public CommonResult householdMigrate(VResPop vResPop, OperationLog operationLog) {
        Population population = new Population(vResPop);
        ResPop resPop = new ResPop(vResPop);
        //校验传人信息和数据库信息是否对应
        CommonResult checkPop = populationService.checkPop(population);
        if (checkPop.getCode() != 1) {
            checkPop.setCode(Errors.ERROR_RES_IDCARD);
            return checkPop;
        }
        //更新population表中内容
        CommonResult updatePop = populationService.updatePop(population);
        if (updatePop.getCode() != 1) {
            updatePop.setCode(Errors.ERROR_RES_IDCARD);
            return updatePop;
        }
        //检索此人是不是常住人口，如果不是则是新增respop，如果是则是更新
        CommonResult nowResPop = resPopService.selectRPBYPopId(((Population) checkPop.getResult()).getId());
        //根据popid更新Respop表
        population = (Population) checkPop.getResult();//获取到当前用户的id给popid赋值
        resPop.setPopId(population.getId());
        if (nowResPop.getCode() != 1) {
            //如果不存在则是其它人口迁入，变为常住人口执行insert操作
            CommonResult insertResPop = resPopService.insertResPop(resPop);
            if (insertResPop.getCode() != 1) {
                insertResPop.setCode(Errors.ERROR_RES_IDCARD);
                return insertResPop;
            }
        } else {
            //如果存在则更改户号和相关信息
            CommonResult updateRP = resPopService.updateRP(resPop);
            if (updatePop.getCode() != 1) {
                updatePop.setCode(Errors.ERROR_RES_IDCARD);
                return updateRP;
            }
        }
        //插入日志表
        int fillLog = operationLogService.fillOperationLog(operationLog, population.getIdnum());
        if (fillLog != 1) {
            return new CommonResult<>(0, "日志插入失败", null);
        }
        //返回成功结果
        return new CommonResult<>(1, "户口迁移成功", null);
    }

    /**
     * @param houseNum
     * @return CommonResult
     * @description 根据户号查询家庭成员
     * @author 张幸晔
     * @date 2024-06-24 18:44
     */

    @Override
    public CommonResult selectByHouseNum(String houseNum) {
        LambdaQueryWrapper<VResPop> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(VResPop::getHousenum, houseNum).eq(VResPop::getIsDelete, TabelDic.IS_DELETE_NO);
        List<VResPop> vResPops = vResPopMapper.selectList(lambdaQueryWrapper);
        if (vResPops.size() < 0) {
            return new CommonResult<>(0, "查询失败", null);
        }
        return new CommonResult<>(1, "本户号其它家庭成员", vResPops);
    }


    /***
     * @author 张幸晔
     * @date 2024-06-20 10:27
     * @param vResPop
     * @param policeStation
     * @return java.lang.String
     * 生成身份证号
     */
    private String generateIdNum(VResPop vResPop, PoliceStation policeStation) {
        String idNum = "";
        //获取地区前6位
        String district = policeStation.getPNum().substring(0, 6);
        idNum += district;
        //获取生日8位
        String birthday = vResPop.getBirthday().toString().replace("-", "");
        idNum += birthday;
        //从数据库检索当前区当天的顺序号
        String sequence = iIdnumSequenceService.selectIdNumSequence(district, vResPop.getGenderId());
        idNum += sequence;

        Integer one = idNum.charAt(0) - '0';
        Integer two = idNum.charAt(1) - '0';
        Integer three = idNum.charAt(2) - '0';
        Integer four = idNum.charAt(3) - '0';
        Integer five = idNum.charAt(4) - '0';
        Integer six = idNum.charAt(5) - '0';
        Integer seven = idNum.charAt(6) - '0';
        Integer eight = idNum.charAt(7) - '0';
        Integer nine = idNum.charAt(8) - '0';
        Integer ten = idNum.charAt(9) - '0';
        Integer eleven = idNum.charAt(10) - '0';
        Integer twelve = idNum.charAt(11) - '0';
        Integer thirteen = idNum.charAt(12) - '0';
        Integer fourteen = idNum.charAt(13) - '0';
        Integer fifteen = idNum.charAt(14) - '0';
        Integer sixteen = idNum.charAt(15) - '0';
        Integer seventeen = idNum.charAt(16) - '0';

        Integer sum = one * 7 + two * 9 + three * 10 + four * 5 + five * 8 + six * 4 + seven * 2 + eight * 1 + nine * 6 + ten * 3 + eleven * 7 + twelve * 9 + thirteen * 10 + fourteen * 5 + fifteen * 8 + sixteen * 4 + seventeen * 2;
        Integer checkNum = sum % 11;
        if (checkNum != 10) {
            idNum += checkNum;
        } else {
            idNum += "X";
        }
        return idNum;
    }

    @Autowired
    PopulationMapper populationMapper;
    @Autowired
    ResPopMapper resPopMapper;

    @Autowired
    IVFloPopService vFloPopService;
    @Autowired
    IVImpPopService vIMpPopService;
    @Override
    public CommonResult generatepop(Integer num, Integer beginid) {
        Random r = new Random();
        List<Population> populationList = new ArrayList<>();
        List<ResPop> resPopList = new ArrayList<>();

        Long start_id = beginid.longValue();
        List<PoliceStation> policeList = (List<PoliceStation>) (policeStationService.selectAllPolice().getResult());
        // 修改警局
        PoliceStation policeStation=(PoliceStation) policeStationService.selectPoliceStationInfoByPid(8L).getResult();
        policeList.clear();
        policeList.add(policeStation);
        for (int i = 0; i < num; i++) {
            VResPop vResPop = GenerateResPop(populationList, resPopList, start_id, policeList);
            start_id += 1L;
        }
        int k = 0;
        for (int i = 0; i < populationList.size(); i++) {
            for (int j = i + 1; j < populationList.size(); j++) {
                if (populationList.get(i).getIdnum().equals(populationList.get(j).getIdnum())) {
                    populationList.remove(j);
                    resPopList.remove(j);
                    System.out.println("重复了");
                    k++;
                }

            }
        }
        if (k != 0) {
            return new CommonResult<>(0, "有重复身份证号", null);
        }
        populationMapper.insertPopList(populationList);
        resPopMapper.insertResPopList(resPopList);
//
//        int change_size = r.nextInt(num);
//        System.out.println("类型变更：" + change_size);
//        for (int i = 0; i < change_size; i++) {
//            if (r.nextInt(2) == 0) {
//                VFloPop vFloPop = new VFloPop();
//                vFloPop.setName(populationList.get(i).getName());
//                vFloPop.setIdnum(populationList.get(i).getIdnum());
//                vFloPop.setBirthday(populationList.get(i).getBirthday());
//                vFloPop.setGenderId(populationList.get(i).getGenderId());
//                vFloPop.setNationId(populationList.get(i).getNationId());
//                vFloPop.setBloodId(populationList.get(i).getBloodId());
//                vFloPop.setEduId(populationList.get(i).getEduId());
//                vFloPop.setMarryId(populationList.get(i).getMarryId());
//                vFloPop.setDisabilityId(populationList.get(i).getDisabilityId());
//                vFloPop.setMilitaryId(populationList.get(i).getMilitaryId());
//                vFloPop.setAddress(populationList.get(i).getAddress());
//                vFloPop.setPopTypeId(3L);
//                vFloPop.setLivedate(LocalDate.of(2024 + r.nextInt(33), 1 + r.nextInt(12), 1 + r.nextInt(28)));
//                vFloPop.setLivereason("秦皇岛太美了");
//                vFloPop.setLiveaddress("燕山大学");
//                vFloPop.setIsDelete(0);
//                OperationLog log=new OperationLog();
//                log.setPid(4L);
//                log.setOperatorId(4L);
//                log.setChangetype("流动人口信息采集（自动）");
//                log.setChangereson("自动生成数据");
//
//                vFloPopService.insertVFLo(vFloPop,log);
//            }
//        }
//        System.out.println(populationList);
//        System.out.println(resPopList);
//        System.out.println(k);
//        populationMapper.insertPopList(populationList);
        return new CommonResult<>(populationList);
    }

    private VResPop GenerateResPop(List<Population> populationList, List<ResPop> resPopList, Long start_id, List<PoliceStation> policeList) {
        VResPop vResPop = new VResPop();
        Random r = new Random();
        // 随机生成姓名
        vResPop.setId(start_id);

        vResPop.setName(generateChineseCharacters(r.nextInt(2) + 2));
        vResPop.setBirthday(LocalDate.of(1990 + r.nextInt(33), 1 + r.nextInt(12), 1 + r.nextInt(28)));
        vResPop.setGenderId(r.nextInt(2)+1);

        vResPop.setNationId(generateRandomLongInRange(1, 59));
        vResPop.setBloodId(generateRandomLongInRange(1, 5));
        vResPop.setEduId(generateRandomLongInRange(1, 11));
        vResPop.setMarryId(generateRandomLongInRange(1, 5));
        vResPop.setDisabilityId(generateRandomLongInRange(1, 9));
        vResPop.setMilitaryId(generateRandomLongInRange(1, 5));
        vResPop.setAddress("河北省秦皇岛市经济技术开发区船厂路街道人口小区10号");
        vResPop.setPopTypeId(1L);
        vResPop.setHousenum("000000008");// 统一一个户，省的立户了，只不过这个户人有点多了
        vResPop.setHousetypeId(1L);
        vResPop.setRelationId(3L);
        vResPop.setWork("");
        vResPop.setServicePlace("");
        vResPop.setIsDelete(TabelDic.IS_DELETE_NO);
        // 检索所有警局，随机选择一个

//        PoliceStation p = policeList.get(r.nextInt(policeList.size()));
        PoliceStation p = policeList.get(0);

        vResPop.setIdnum(generateIdNum(vResPop, p));

        Population population = new Population(vResPop);
        population.setCreateTime(LocalDateTime.now());

        ResPop resPop = new ResPop(vResPop);
        resPop.setCreateTime(LocalDateTime.now());

        populationList.add(population);
        resPopList.add(resPop);
        return vResPop;
    }

    /**
     * 范围是 [min,max)
     *
     * @param min
     * @param max
     * @return java.lang.Long
     * @author 赵子鉴
     * @date 2024-06-25 18:12
     */
    public static Long generateRandomLongInRange(long min, long max) {
        Random random = new Random();
        return min + (long) (random.nextDouble() * (max - min));
    }

    private static final String FIRST_CHARACTERS = "赵钱孙李周吴郑王冯陈褚卫蒋沈韩杨朱秦尤许何吕施张孔曹严华金魏陶姜戚谢邹喻柏" +
            "水窦章云苏潘葛奚范彭郎鲁韦昌马苗凤花方俞任袁柳酆鲍史唐费廉岑薛雷贺倪汤滕殷罗毕郝邬安常乐于时傅皮卞齐康伍余元卜顾孟平黄和穆萧尹" +
            "姚邵湛汪祁毛禹狄米贝明臧计伏成戴谈宋茅庞熊纪舒屈项祝董梁杜阮蓝闵席季麻强贾路娄危江童颜郭梅盛林刁钟徐邱骆高夏蔡田樊胡凌霍虞万" +
            "支柯昝管卢莫经房裘缪干解应宗丁宣贲邓郁单杭洪包诸左石崔吉钮龚程嵇邢滑裴陆荣翁荀羊於惠甄曲家封芮羿储靳汲邴糜松井段富巫乌焦巴弓" +
            "牧隗山谷车侯宓蓬全郗班仰秋仲伊宫宁仇栾暴甘钭厉戎祖武符刘景詹束龙叶幸司韶郜黎蓟薄印宿白怀蒲邰从鄂索咸籍赖卓蔺屠蒙池乔阴鬱胥" +
            "能苍双闻莘党翟谭贡劳逄姬申扶堵冉宰郦雍郤璩桑桂濮牛寿通边扈燕冀郏浦尚农温别庄晏柴瞿阎充慕连茹习宦艾鱼容向古易慎戈廖庾终暨居" +
            "衡步都耿满弘匡国文寇广禄阙东欧殳沃利蔚越夔隆师巩厍聂晁勾敖融冷訾辛阚那简饶空曾毋沙乜养鞠须丰巢关蒯相查后荆红游竺权逯盖益桓公" +
            "万俟司马上官欧阳夏侯诸葛闻人东方赫连皇甫尉迟公羊澹台公冶宗政濮阳淳于单于太叔申屠公孙仲孙轩辕令狐钟离宇文长孙慕容鲜于闾丘司徒" +
            "司空丌官司寇仉督子车颛孙端木漆雕乐正壤驷公良拓跋夹谷宰父谷梁晋楚闫法汝鄢涂钦段干百里东郭南门呼延归海羊舌微生岳帅缑亢况郈有琴" +
            "梁丘左丘东门西门商牟佘佴伯赏南宫墨哈谯笪年爱阳佟第五言福";
    private static final int MIN_FIRST_CHARACTER_INDEX = 0;
    private static final int MAX_FIRST_CHARACTER_INDEX = FIRST_CHARACTERS.length() - 1;

    public static String generateChineseCharacters(int count) {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();

        // 生成第一个汉字
        int firstCharIndex = random.nextInt(MAX_FIRST_CHARACTER_INDEX - MIN_FIRST_CHARACTER_INDEX + 1) + MIN_FIRST_CHARACTER_INDEX;
        sb.append(FIRST_CHARACTERS.charAt(firstCharIndex));

        // 生成剩余的汉字
        for (int i = 1; i < count; i++) {
            sb.append(generateChineseCharacter());
        }
        return sb.toString();
    }

    private static String generateChineseCharacter() {
        String str = "";
        int highPos, lowPos;

        // 随机生成汉字的两个字节
        Random random = new Random();
        highPos = (176 + Math.abs(random.nextInt(39))); //获取高位值
        lowPos = (161 + Math.abs(random.nextInt(93))); //获取低位值

        byte[] b = new byte[2];
        b[0] = (new Integer(highPos)).byteValue();
        b[1] = (new Integer(lowPos)).byteValue();

        try {
            str = new String(b, "GB2312"); //转换成汉字
        } catch (Exception e) {
            e.printStackTrace();
        }

        return str;
    }

    public static void main(String[] args) {
//        for (int i = 0; i < 1000; i++) {
//            System.out.println(generateChineseCharacters(2));
//            System.out.println(generateChineseCharacters(3));
//        }


    }

    private static void validateIDCard(String idCard) {
        // 验证身份证号长度和格式
        if (idCard.length() != 18 || !idCard.matches("^\\d{17}[0-9Xx]$")) {
            System.out.println("身份证号格式不合法");
            return;
        }

        // 验证出生日期合法性
        int year = Integer.parseInt(idCard.substring(6, 10));
        int month = Integer.parseInt(idCard.substring(10, 12));
        int day = Integer.parseInt(idCard.substring(12, 14));
        LocalDate birthDate = LocalDate.of(year, month, day);
        if (birthDate.isAfter(LocalDate.now())) {
            System.out.println("身份证号的出生日期不合法");
            return;
        }

        // 验证最后一位校验码
        int[] weightFactors = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
        int sum = 0;
        for (int i = 0; i < 17; i++) {
            sum += Integer.parseInt(String.valueOf(idCard.charAt(i))) * weightFactors[i];
        }
        int checkDigit = sum % 11;
        char checkCode = idCard.charAt(17);
        if (checkDigit == 0 && checkCode != '1' || checkDigit != 0 && checkCode != String.valueOf(12 - checkDigit).charAt(0)) {
            System.out.println("身份证号的校验码不合法");
            return;
        }

        // 计算年龄
        int age = Period.between(birthDate, LocalDate.now()).getYears();
        System.out.println("身份证号合法,持有人年龄为: " + age);
    }
}
